package com.ruoyi.info.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.io.file.FileNameUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.util.security.SandboxResult;
import com.ruoyi.util.security.SandboxUtil;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.util.security.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.info.mapper.CmsSandboxMapper;
import com.ruoyi.info.domain.CmsSandbox;
import com.ruoyi.info.service.ICmsSandboxService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.web.multipart.MultipartFile;

/**
 * sandboxService业务层处理
 * 
 * @author xwj
 * @date 2023-08-07
 */
@Service
public class CmsSandboxServiceImpl implements ICmsSandboxService 
{
    @Autowired
    private CmsSandboxMapper cmsSandboxMapper;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询sandbox
     * 
     * @param id sandbox主键
     * @return sandbox
     */
    @Override
    public CmsSandbox selectCmsSandboxById(Long id)
    {
        return cmsSandboxMapper.selectCmsSandboxById(id);
    }

    /**
     * 查询sandbox列表
     * 
     * @param cmsSandbox sandbox
     * @return sandbox
     */
    @Override
    public List<CmsSandbox> selectCmsSandboxList(CmsSandbox cmsSandbox)
    {
        return cmsSandboxMapper.selectCmsSandboxList(cmsSandbox);
    }

    /**
     * 新增sandbox
     * 
     * @param cmsSandbox sandbox
     * @return 结果
     */
    @Override
    public int insertCmsSandbox(CmsSandbox cmsSandbox)
    {
        cmsSandbox.setCreateTime(DateUtils.getNowDate());
        return cmsSandboxMapper.insertCmsSandbox(cmsSandbox);
    }

    /**
     * 修改sandbox
     * 
     * @param cmsSandbox sandbox
     * @return 结果
     */
    @Override
    public int updateCmsSandbox(CmsSandbox cmsSandbox)
    {
        cmsSandbox.setUpdateTime(DateUtils.getNowDate());
        return cmsSandboxMapper.updateCmsSandbox(cmsSandbox);
    }

    /**
     * 批量删除sandbox
     * 
     * @param ids 需要删除的sandbox主键
     * @return 结果
     */
    @Override
    public int deleteCmsSandboxByIds(String ids)
    {
        return cmsSandboxMapper.deleteCmsSandboxByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除sandbox信息
     * 
     * @param id sandbox主键
     * @return 结果
     */
    @Override
    public int deleteCmsSandboxById(Long id)
    {
        return cmsSandboxMapper.deleteCmsSandboxById(id);
    }

    @Override
    public AjaxResult uploadApp(SysUser currUser, MultipartFile mfile, String os) throws Exception {
        String filePath = RuoYiConfig.getProfile() + "/app";
        String profile = RuoYiConfig.getProfile();

        String fileName = FileUploadUtils.upload(filePath, mfile, null);

        String fileName2 = fileName.replace(Constants.RESOURCE_PREFIX, "");
        String localPath = profile + fileName2;

        File file = new File(localPath);

        String host = configService.selectConfigByKey("sandbox.host");
        String token = configService.selectConfigByKey("sandbox.token");

        SandboxResult result = SandboxUtil.submitTask(host, token, file, os);

        Integer code = result.getCode();
        String message = result.getMessage();
        String data = result.getData();

        if(code != null && code != 0) {
            return AjaxResult.error(message);
        }

        if(code == null && result.getNon_field_errors() != null) {
            if(result.getNon_field_errors().size() > 0) {
                return AjaxResult.error(result.getNon_field_errors().get(0));
            }
            return AjaxResult.error("提交任务检测失败！");
        }

        JSONObject jo = JSON.parseObject(data);
        JSONObject joInner = jo.getJSONObject(file.getName());

        String taskId = joInner.getString("task_id");
        String inenrMessage = joInner.getString("message");

        if(StringUtils.isEmpty(taskId) || "0".equals(taskId)) {
            return AjaxResult.error(inenrMessage);
        }


        CmsSandbox sandbox = new CmsSandbox();
        sandbox.setUserId(currUser.getUserId());
        sandbox.setOs(os);
        sandbox.setFileName(file.getName());
        sandbox.setFileType(FileNameUtil.extName(file));
        sandbox.setCode(code + "");
        sandbox.setResult(data);
        sandbox.setTaskId(taskId);

        insertCmsSandbox(sandbox);

        return AjaxResult.success();
    }

    @Override
    public SandboxResult getSandboxResult(CmsSandbox sandbox) {
        String host = configService.selectConfigByKey("sandbox.host");
        String token = configService.selectConfigByKey("sandbox.token");

        SandboxResult result = SandboxUtil.reportOverview(host, token, sandbox.getTaskId());

        return result;
    }

    @Override
    public SandboxResult getSandboxTags(CmsSandbox sandbox) {
        String host = configService.selectConfigByKey("sandbox.host");
        String token = configService.selectConfigByKey("sandbox.token");

        SandboxResult result = SandboxUtil.reportTags(host, token, sandbox.getTaskId());

        return result;
    }

    @Override
    public SandboxResult sandboxScreenshot(String taskId) {
        String host = configService.selectConfigByKey("sandbox.host");
        String token = configService.selectConfigByKey("sandbox.token");

        SandboxResult result = SandboxUtil.reportScreenshot(host, token, taskId);

        return result;
    }

    @Override
    public SandboxResult sandboxNetwork(String taskId, Map<String, Object> paramMap) {
        String host = configService.selectConfigByKey("sandbox.host");
        String token = configService.selectConfigByKey("sandbox.token");

        SandboxResult result = SandboxUtil.sandboxNetwork(host, token, taskId, paramMap);

        return result;
    }

    @Override
    public SandboxResult sandboxBehaviorProcess(String taskId, Map<String, Object> params) {
        String host = configService.selectConfigByKey("sandbox.host");
        String token = configService.selectConfigByKey("sandbox.token");

        SandboxResult result = SandboxUtil.sandboxBehaviorProcess(host, token, taskId, params);

        return result;
    }

    @Override
    public SandboxResult sandboxBehaviorEventsByPid(String taskId, String pid, String eventType, Map<String, Object> params) {
        String host = configService.selectConfigByKey("sandbox.host");
        String token = configService.selectConfigByKey("sandbox.token");

        SandboxResult result = SandboxUtil.sandboxBehaviorEventsByPid(host, token, taskId, pid, eventType, params);

        return result;
    }

    @Override
    public SandboxResult sandboxReportStatic(String taskId, Map<String, Object> params) {
        String host = configService.selectConfigByKey("sandbox.host");
        String token = configService.selectConfigByKey("sandbox.token");

        SandboxResult result = SandboxUtil.sandboxReportStatic(host, token, taskId, params);

        return result;
    }
}
